package com.dao;

import java.sql.SQLException;
import java.util.List;
import java.util.Map;

import com.common.tool.CommonConfig;
import com.entity.BaseWeixinSubscribe;
import com.jfinal.kit.PropKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.IAtom;
import com.jfinal.plugin.activerecord.Record;

/**
 * 计算积分
 * 
 * @author mm
 *
 */
public class CalculationScore {

    int saleScore = Integer.valueOf(PropKit.get("distribution_money"));
    int saleScoreCount = Integer.valueOf(PropKit.get("distribution_level"));

    StringBuilder sql = new StringBuilder("select * from weixin_subscribe").append("  where fromusername= '");// 查找此会员信息

    // 计算积分
    public void memberThreeSale(MemberBuy memberBuy) {
	String openId = memberBuy.getOpenid();
	StringBuilder membersql = sql.append(openId).append("'");

	WeixinSubscribe subscribe = WeixinSubscribe.dao.findFirst(membersql.toString());

	// TODO:自己的商铺刚上级会员得不到分销的钱 10
	if (PropKit.get("member_shop").equals(subscribe.getMembertypecode())) {
	    return;
	}

	String parentOpenId = subscribe.getRecommendUsername();
	calculationInThreeLevel(0, parentOpenId, 0, memberBuy);
    }

    // 计算积分规则
    private void calculationInThreeLevel(int i, String parentOpenId, int harvest, MemberBuy memberBuy) {
	if (parentOpenId.isEmpty()) {
	    return;
	} else if (i == saleScoreCount) {
	    return;
	} else {
	    StringBuilder membersql = sql.append(parentOpenId).append("'");
	    WeixinSubscribe subscribe = WeixinSubscribe.dao.findFirst(membersql.toString());
	    if (PropKit.get("member_shop").equals(subscribe.getMembertypecode())) {
		int sumscore = saleScore * saleScoreCount * memberBuy.getNum();
		if (harvest < sumscore) {
		    int now = sumscore - harvest;
		    // insert 添加积分 积分为now
		    insertForkScore(parentOpenId, memberBuy, now);
		    return;
		}
	    } else {
		harvest += saleScore;
		// insert 添加积分 积分为saleScore
		insertForkScore(parentOpenId, memberBuy, saleScore);
		i++;
		calculationInThreeLevel(i, subscribe.getRecommendUsername(), harvest, memberBuy);
	    }

	}
    }

    // 保存积分记录
    private void insertForkScore(String parentOpenId, MemberBuy memberBuy, int money) {
	MemberScoreFork scoreFork = new MemberScoreFork();
	scoreFork.setOpenid(parentOpenId);
	scoreFork.setBuyid(memberBuy.getBuyid());
	scoreFork.setBuyopenid(memberBuy.getOpenid());
	scoreFork.setNum(memberBuy.getNum());
	scoreFork.setScore(Integer.valueOf(money));
	scoreFork.save();
    }

    /**
     * 找出相关子成员 @Title: ListChildMembers @Description:
     * TODO(这里用一句话描述这个方法的作用) @param @param openId @param @return 设定文件 @return
     * List<WeixinSubscribe> 返回类型 @throws
     */
    private List<WeixinSubscribe> ListChildMembers(String openId) {
	StringBuilder sql = new StringBuilder("select * from weixin_subscribe ");
	sql.append("where FIND_IN_SET(recommend_username,queryChildrenOpenId('").append(openId).append("')");
	return WeixinSubscribe.dao.find(sql.toString());
    }
    
    /**
     * 添加商户下的会员
    * @Title: saveChildMember 
    * @Description: TODO(这里用一句话描述这个方法的作用) 
    * @param @param WeixinSubscribelst
    * @param @param shopOpenId    设定文件 
    * @return void    返回类型 
    * @throws
     */
    public void saveChildMember(final List<WeixinSubscribe> WeixinSubscribelst, final String shopOpenId) {

	Db.tx(new IAtom() {
	    @Override
	    public boolean run() throws SQLException {
		boolean saveDataResult = true;
		int i = 0;
		for (WeixinSubscribe subscribe : WeixinSubscribelst) {
		    i++;
		    MemberShop shop = new MemberShop();
		    shop.setShopopenid(shopOpenId);
		    shop.setMemberid(subscribe.getUserId());
		    shop.setMemberlevel(i);
		    shop.setMemberopenid(subscribe.getFromusername());
		    shop.setParentopenid(subscribe.getRecommendUsername());
		    shop.setMemberstate(CommonConfig.RECORD_VALIDATE);
		    if(PropKit.get("member_shop").equals(subscribe.getMembertypecode())){
			break;
		    }
		    saveDataResult = saveDataResult && MemberShop.dao.save(); // 将所有结果与，只要有一条失败就跳出循环，返回false
		    if (!saveDataResult) {
			break;
		    }
		}
		return saveDataResult;
	    }

	});

    }

}
